local skynet = require "skynet"
local socket = require "socket"

local fd

local CMD = {}

function CMD.broadcast(msg)
  if fd then
    socket.write(fd, msg .. "\n")
  end
end

skynet.start(function()
  skynet.dispatch("lua", function(_, _, cmd, ...)
    local f = CMD[cmd]
    if f then
      skynet.retpack(f(...))
    elseif cmd == "start" then
      fd = ...
      skynet.error("[echo] client fd", fd)
      socket.start(fd)

      while true do
        local msg = socket.read(fd)
        if msg then
          skynet.error("[echo] recv", msg)
          socket.write(fd, msg) -- echo back
        else
          skynet.error("[echo] client closed", fd)
          skynet.send(".main", "lua", "client_exit", fd)
          socket.close(fd)
          skynet.exit()
        end
      end
    end
  end)
end)
